package com.example.teamtribe.main.club.clubintroduce.media;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.teamtribe.common.Back;
import com.example.teamtribe.common.model.FileModel;
import com.example.teamtribe.database.Media;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lenovo on 2018/6/3.
 */

public class MediaPresenter implements MediaContract.Presenter {
    private MediaContract.View view;
    private MediaModel model;

    public MediaPresenter(MediaContract.View view) {
        this.view = view;
        model =MediaModel.getInstance();
    }

    @Override
    public void getMedia(int mediaId,final int type) {
        model.getMedia(mediaId, new FileModel.FileBack() {
            @Override
            public void loadSuccess(String fileName) {view.setCover();}

            @Override
            public void success(@Nullable Bundle bundle) {
                Media media=bundle.getParcelable("media");
                media.saveOrUpdate("realId=?",media.getRealId()+"");
                if(media.getType()==type)
                view.addMedia(media);
            }

            @Override
            public void failure(String meg) {
                view.showToast(meg);
                view.finishRefresh();
            }
        });
    }

    @Override
    public void getMedias(int teamId,int type) {
        Log.d("zsm", "getMedias: "+type);
        List<Media> medias = model.getLocalMedias(teamId,type);
        for(Media m:medias)
            Log.d("zsm", m.toString());
        if (medias == null || medias.isEmpty()) {
            refreshMedias(teamId,type);
        }else{
            view.setMedias(medias);
        }
    }

    @Override
    public void refreshMedias(int teamId,final int type) {
        Log.d("zsm", "refreshMedias: "+type);
        model.getMediaIds(teamId, new Back() {
            @Override
            public void success(@Nullable Bundle bundle) {
                ArrayList<Integer> ids = bundle.getIntegerArrayList("ids");
                model.clearLocalMedias(type);
                view.clearMedias();
                if(ids.isEmpty()){
                    view.finishRefresh();
                    return;
                }
                for (int i = 0; i < ids.size(); i++) {
                    getMedia(ids.get(i),type);
                    if (i == ids.size() - 1) {
                        view.finishRefresh();
                    }
                }
            }

            @Override
            public void failure(String meg) {
                view.finishRefresh();
                view.showToast(meg);
            }
        });
    }
}
